﻿#include "changepasswordwidget.h"
#include "ui_changepasswordwidget.h"
#include <QMessageBox>
#include <QDebug>

ChangePasswordWidget::ChangePasswordWidget(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ChangePasswordWidget)
{
    ui->setupUi(this);

    setWindowTitle("修改密码");

    setTabOrder(ui->lineEditPassword, ui->lineEditPassword1);
    setTabOrder(ui->labelPassword1, ui->lineEditPassword2);
    setTabOrder(ui->lineEditPassword2, ui->pushButtonSubmit);
    setTabOrder(ui->pushButtonSubmit, ui->pushButtonCancel);

    connect(&manager, &BaseNetworkAccessManager::onSuccessWithData,
            [=](QString message, QJsonObject data)
    {
        QString newPassword = data.value("newPassword").toString();
        if(passwordType == Tools::LoginPassword){
            MySettings.setValue("user/password", newPassword);
        }else{
            MySettings.setValue("user/operatePassword", newPassword);
        }
        QMessageBox::information(this, "信息", message);
        this->close();
    });

    connect(&manager, &BaseNetworkAccessManager::onFailed,
            [=](const QString message)
    {
        QMessageBox::warning(this, "警告", message);
    });
}

ChangePasswordWidget::~ChangePasswordWidget()
{
    delete ui;
}

void ChangePasswordWidget::setPasswordType(Tools::PasswordType passwordType)
{
    this->passwordType = passwordType;
    if(passwordType == Tools::LoginPassword){
        setWindowTitle("修改登录密码");
    }else{
        setWindowTitle("修改操作密码");
    }
}

void ChangePasswordWidget::on_pushButtonCancel_clicked()
{
    this->close();
}

void ChangePasswordWidget::on_pushButtonSubmit_clicked()
{
    QString oldPassword = ui->lineEditPassword->text();
    QString password1 = ui->lineEditPassword1->text();
    QString password2 = ui->lineEditPassword2->text();

    if(oldPassword.isEmpty() || password1.isEmpty() || password2.isEmpty()){
        QMessageBox::warning(this, "警告", "输入内容不能为空");
        return;
    }

    if(password1 != password2){
        QMessageBox::warning(this, "警告", "两次输入密码不同");
        return;
    }

    QString username = MySettings.value("user/username").toString();

    manager.changePassword(oldPassword, password1, passwordType);
}
